// 引入 IOutboundItem 和 ICategory 类型定义，最好是放在一个共享的 types.ts 文件中
// 这里为了方便，直接复制
interface ICategory {
  id: number;
  name: string;
  unit: string;
  unitPrice: number;
}
interface IOutboundItem {
  key: number;
  categoryId: number | null;
  name: string;
  unit: string;
  unitPrice: number;
  quantity: string;
  totalPrice: string;
  billingType?: 'PAID' | 'CHARITY';
}

Page({
  data: {
    // 模拟的品类数据，实际项目中应从 API 获取
    allCategories: [
      { id: 1, name: '黄纸板', unit: '公斤', unitPrice: 1.1 },
      { id: 2, name: '塑料水瓶', unit: '公斤', unitPrice: 2.5 },
      { id: 3, name: '废铁', unit: '公斤', unitPrice: 3.2 },
      { id: 4, name: '旧报纸', unit: '公斤', unitPrice: 0.8 },
      { id: 5, name: '易拉罐', unit: '个', unitPrice: 0.1 },
    ] as ICategory[],
    allParticipants: [
      { id: 101, name: '张三', avatar: 'https://mp-7734cf55-8926-4ed0-a608-1302ac9a2a87.cdn.bspapp.com/avatar.png', isSelected: false },
      { id: 102, name: '李四', avatar: 'https://mp-7734cf55-8926-4ed0-a608-1302ac9a2a87.cdn.bspapp.com/avatar.png', isSelected: false },
      { id: 103, name: '王五回', avatar: 'https://mp-7734cf55-8926-4ed0-a608-1302ac9a2a87.cdn.bspapp.com/avatar.png', isSelected: false },
      { id: 104, name: '王收', avatar: 'https://mp-7734cf55-8926-4ed0-a608-1302ac9a2a87.cdn.bspapp.com/avatar.png', isSelected: false },
      { id: 105, name: '往挖洞', avatar: 'https://mp-7734cf55-8926-4ed0-a608-1302ac9a2a87.cdn.bspapp.com/avatar.png', isSelected: false },
    ] as IParticipant[],
    selectedParticipantIds: [] as number[],
    outboundList: [] as IOutboundItem[],
    totalAmount: '0.00',

    paymentMethods: [
      { name: '现金', value: 'CASH' },
      { name: '微信', value: 'WECHAT' },
      { name: '支付宝', value: 'ALIPAY' },
      { name: '对公转账', value: 'TRANSFER' },
    ],
    paymentMethod: '',

    photos: [] as string[],
    remarks: '',

    isLoading: false,
  },

  onLoad() {
    // 页面加载时自动添加一个空条目，引导用户操作
    this.addItem();
  },

  // 监听子组件的 'update' 事件
  onItemUpdate(e: WechatMiniprogram.CustomEvent) {
    const { index, item } = e.detail;
    this.setData({
      [`outboundList[${index}]`]: item
    });
    this.calculateGrandTotal();
  },

  // 监听子组件的 'delete' 事件
  onItemDelete(e: WechatMiniprogram.CustomEvent) {
    const { index } = e.detail;
    wx.showModal({
      title: '确认删除',
      content: '确定要删除此条目吗？',
      confirmColor: '#f56c6c',
      success: (res) => {
        if (res.confirm) {
          this.data.outboundList.splice(index, 1);
          this.setData({
            outboundList: this.data.outboundList
          });
          this.calculateGrandTotal();
        }
      }
    });
  },
  // 选择参与人员
  toggleParticipant(e: WechatMiniprogram.TouchEvent) {
    const id = e.currentTarget.dataset.id as number;
    const { allParticipants } = this.data;

    // 找到被点击的参与者，并更新其 isSelected 状态
    const newParticipants = allParticipants.map(p => {
      if (p.id === id) {
        return { ...p, isSelected: !p.isSelected };
      }
      return p;
    });

    // 根据新的参与者列表，重新计算 selectedParticipantIds
    const newSelectedIds = newParticipants
      .filter(p => p.isSelected)
      .map(p => p.id);

    this.setData({
      allParticipants: newParticipants,
      selectedParticipantIds: newSelectedIds,
    });
  },
  // 添加一个新的出货条目
  addItem() {
    const newItem: IOutboundItem = {
      key: Date.now() + Math.random(), // 生成唯一key
      categoryId: null,
      name: '',
      unit: '',
      unitPrice: 0,
      quantity: '',
      totalPrice: '0.00'
    };
    this.data.outboundList.push(newItem);
    this.setData({
      outboundList: this.data.outboundList
    });
  },

  // 计算总价
  calculateGrandTotal() {
    const total = this.data.outboundList.reduce((sum, item) => {
      return sum + (parseFloat(item.totalPrice) || 0);
    }, 0);
    this.setData({
      totalAmount: total.toFixed(2)
    });
  },

  // 收款方式变更
  onPaymentChange(e: WechatMiniprogram.CustomEvent) {
    this.setData({ paymentMethod: e.detail.value });
  },

  // 上传照片
  uploadPhoto() {
    const count = 3 - this.data.photos.length;
    if (count <= 0) return;

    wx.chooseMedia({
      count,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePaths = res.tempFiles.map(file => file.tempFilePath);
        this.setData({
          photos: [...this.data.photos, ...tempFilePaths]
        });
      }
    });
  },

  // 预览图片
  previewImage(e: WechatMiniprogram.TouchEvent) {
    const currentUrl = e.currentTarget.dataset.src;
    wx.previewImage({
      current: currentUrl,
      urls: this.data.photos,
    });
  },

  // 删除照片
  removePhoto(e: WechatMiniprogram.TouchEvent) {
    const index = e.currentTarget.dataset.index;
    this.data.photos.splice(index, 1);
    this.setData({
      photos: this.data.photos
    });
  },

  // 备注输入
  onRemarksInput(e: WechatMiniprogram.CustomEvent) {
    this.setData({ remarks: e.detail.value });
  },

  // 提交表单
  submitForm() {
    // 1. 校验
    if (parseFloat(this.data.totalAmount) <= 0) {
      wx.showToast({ title: '出货总价必须大于0', icon: 'none' });
      return;
    }
    if (!this.data.paymentMethod) {
      wx.showToast({ title: '请选择收款方式', icon: 'none' });
      return;
    }

    // 2. 设置加载状态
    this.setData({ isLoading: true });

    // 3. 准备提交数据
    const submitData = {
      items: this.data.outboundList.filter(item => item.categoryId && parseFloat(item.quantity) > 0), // 过滤掉无效条目
      totalAmount: this.data.totalAmount,
      paymentMethod: this.data.paymentMethod,
      photoUrls: this.data.photos, // 实际项目中需要先上传图片获取URL
      remarks: this.data.remarks
    };

    console.log('准备提交的数据:', submitData);

    // 4. 模拟API请求
    setTimeout(() => {
      this.setData({ isLoading: false });
      wx.showToast({
        title: '出货成功',
        icon: 'success',
        duration: 2000
      });
      // 成功后可以跳转页面
      // wx.redirectTo({ url: '/pages/success/success' });
    }, 1500);
  }
});
